﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MvcEngine.Core;
using MvcEngine.Core.Repositories;
using System.Data.Linq;
using MvcEngine.Core.Account;
using MvcEngine.Core.Pagination;
using MvcEngine.Core.Base;
using MvcEngine.Core.Extensions;

namespace MvcEngine.LinqToSqlProvider
{
    public class RoleRepository : BaseRepository<Role>, IRoleRepository
    {
        public Role Get(string name, Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Roles().SingleOrDefault(r => r.Name == name && r.SiteId == siteId);
            }
        }

        public IList<Role> GetAllByUser(string userName, Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return (from r in contextManager.Context.Roles()
                        join
                            ur in contextManager.Context.UserInRoles() on r.Id equals ur.RoleId
                        join
                            u in contextManager.Context.Users() on ur.UserId equals u.Id
                        where u.Name == userName && u.SiteId == siteId
                        select r).ToList();
            }
        }

        public IList<Role> GetAllByUser(Guid userId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return (from r in contextManager.Context.Roles() join
                            ur in contextManager.Context.UserInRoles() on r.Id equals ur.RoleId join
                            u in contextManager.Context.Users() on ur.UserId equals u.Id
                            where u.Id == userId
                        select r).ToList();
            }
        }

        public void Add(Role entity)
        {
            throw new NotImplementedException();
        }

        public IPagination<Role> GetAll(int pageIndex, int count, Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Roles().Where(t => ((IUnique)t).SiteId == siteId).GetPage(pageIndex, count);
            }
        }

        public IList<Role> GetAll(Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Roles().Where(r => r.SiteId == siteId).ToList();
            }
        }
    }
}
